Completed
Push — master ( aebb65...293129 )
by Mark
20s queued 12s
created

Relation   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 27
dl 0
loc 38
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
B getRelationalFields 0 3 6
A tableSetup 0 3 1
1
import Field from "./Field";
2
import ForeignKey from "./Field/ForeignKey";
3
import {ModelStaticInterface, TableInterface} from "../../JeloquentInterfaces";
4
5
/**
6
 *
7
 */
8
export default class Relation extends Field {
9
10
    foreignKey: string;
11
12
    model: ModelStaticInterface;
13
14
    constructor(model: ModelStaticInterface, foreignKey: string = null, name: string = null) {
15
        const className = name ?? model.snakeCaseClassName;
16
        super(className);
17
        this.model = model;
18
        this.foreignKey = foreignKey;
19
    }
20
21
    set _value(value: Record<string, unknown>|Record<string, unknown>[]) {
22
        if (!Array.isArray(value)) {
23
            value = [value];
24
        }
25
26
        value.forEach((modelValue) => {
27
            // todo should use primary key names
28
            // should contain primary key names
29
            // maybe add static model helper
30
            if (!(this.model.ids().includes(`${modelValue?.id}`))) {
31
                this.model.insert(modelValue);
32
            }
33
        });
34
    }
35
36
    getRelationalFields(): ForeignKey[] {
37
        return [new ForeignKey(this.foreignKey).setRelation(this)];
38
    }
39
40
    tableSetup(table: TableInterface): void {
41
        table.registerIndex(this.foreignKey);
42
    }
43
}